from dataclasses import InitVar
from tkinter.filedialog import askdirectory
from tkinter import scrolledtext
import tkinter as tk
import tkinter.ttk
import threading
import calendar
from turtle import bgcolor
import pandas as pd
import numpy as np
import paramiko
import psycopg2
import datetime
import time
import re
import os

# get sentinel2 tile list
def get_tiles(province):
	con = psycopg2.connect(
	database="sentinel2",
	user="postgres",
	password="12345",
	host="192.168.2.172",
	port="5432"
	)
	cur = con.cursor()
	sql = f"""
	SELECT "中国有效哨兵格网分布wgs84".mgrs
	FROM china_sy
	JOIN "中国有效哨兵格网分布wgs84" 
	on st_intersects(china_sy.geom,"中国有效哨兵格网分布wgs84".geom)
	WHERE  china_sy.qhmc = '{province}' 
	"""
	cur.execute(sql)
	con.commit()
	tiles=[record[0] for record in cur.fetchall()]
	tiles = [tile.upper() for tile in tiles]
	cur.close()
	con.close()
	return tiles

# get sentinel2 tile list
def get_province_tiles(province):
	con = psycopg2.connect(
	database="sentinel2",
	user="postgres",
	password="12345",
	host="192.168.2.172",
	port="5432"
	)
	cur = con.cursor()
	sql = f"""
	SELECT "中国有效哨兵格网分布wgs84".mgrs
	FROM china_sy
	JOIN "中国有效哨兵格网分布wgs84" 
	on st_intersects(china_sy.geom,"中国有效哨兵格网分布wgs84".geom)
	WHERE  china_sy.qhmc = '{province}' 
	"""
	cur.execute(sql)
	con.commit()
	tiles=[record[0] for record in cur.fetchall()]
	tiles = [tile.upper() for tile in tiles]
	cur.close()
	con.close()
	return tiles

# get sentinel2 tile list
def get_city_tiles(province, city):
    con = psycopg2.connect(
    database="sentinel2",
    user="postgres",
    password="12345",
    host="192.168.2.172",
    port="5432"
    )
    cur = con.cursor()
    sql = f"""
    SELECT "中国有效哨兵格网分布wgs84".mgrs
    FROM china_dsy
    JOIN "中国有效哨兵格网分布wgs84" 
    on st_intersects(china_dsy.geom,"中国有效哨兵格网分布wgs84".geom)
    WHERE  china_dsy.qhmc = '{city}' 
    AND sjxzqdm in (
        SELECT qhdm
        FROM china_sy
        WHERE  china_sy.qhmc = '{province}' 
    )
    """
    cur.execute(sql)
    con.commit()
    tiles=[record[0] for record in cur.fetchall()]
    tiles = [tile.upper() for tile in tiles]
    cur.close()
    con.close()
    return tiles

# get sentinel2 tile list
def get_county_tiles(province, city, county):
    con = psycopg2.connect(
    database="sentinel2",
    user="postgres",
    password="12345",
    host="192.168.2.172",
    port="5432"
    )
    cur = con.cursor()
    sql = f"""
    SELECT "中国有效哨兵格网分布wgs84".mgrs
    FROM china_xy
    JOIN "中国有效哨兵格网分布wgs84" 
    on st_intersects(china_xy.geom,"中国有效哨兵格网分布wgs84".geom)
    WHERE  china_xy.qhmc = '{county}' 
    AND sjxzqdm in (
        SELECT qhdm
        FROM china_dsy
        WHERE qhmc = '{city}'
        AND sjxzqdm in (
            SELECT qhdm
            FROM china_sy
            WHERE china_sy.qhmc = '{province}'
        )  
    )
    """
    cur.execute(sql)
    con.commit()
    tiles=[record[0] for record in cur.fetchall()]
    tiles = [tile.upper() for tile in tiles]
    cur.close()
    con.close()
    return tiles

# get province list
def get_province_list():
    con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
    )
    cur = con.cursor()
    sql = f"""
    SELECT qhmc
    FROM china_sy
    """
    cur.execute(sql)
    con.commit()

    provinces=[record[0] for record in cur.fetchall()]
    cur.close()
    con.close()
    return provinces

# select city list
def select_city_list(province):
    con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
    )
    cur = con.cursor()
    sql = f"""
    SELECT qhmc
    FROM china_dsy
    WHERE sjxzqdm in (
        SELECT qhdm
        FROM china_sy
        WHERE qhmc = '{province}'
    )
    """
    cur.execute(sql)
    con.commit()
    citys=[record[0] for record in cur.fetchall()]
    cur.close()
    con.close()
    return citys

# select county list
def select_county_list(province, city):
    con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
    )
    cur = con.cursor()
    sql = f"""
        SELECT qhmc
        FROM china_xy
        WHERE sjxzqdm in (
            SELECT qhdm
            FROM china_dsy
            WHERE qhmc = '{city}' AND sjxzqdm in (
                SELECT qhdm
                FROM china_sy
                WHERE qhmc = '{province}'
            )
        )
    """
    cur.execute(sql)
    con.commit()
    countys=[record[0] for record in cur.fetchall()]
    cur.close()
    con.close()
    return countys

# select sentinel2 l1c zip file path
def select_tile_date_zips(tile, date, maxcloud=100):
	con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
	)
	cur = con.cursor()
	sql = f"""
        SELECT path
        FROM l1c_zip_info 
        WHERE shot_date = to_date('{date}','yyyy-mm-dd')
        AND tile = '{tile}'
        AND clouds <= {maxcloud}
	"""
	cur.execute(sql)
	con.commit()
	paths = [record[0] for record in cur.fetchall()]
	cur.close()
	con.close()
	return paths

# select sentinel2 l1c zip file path
def select_zip_paths(tiles, start_date, end_date, maxcloud):
	tiles ="{" +",".join(tiles)+"}"
	con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
	)
	cur = con.cursor()
	sql = f"""
        SELECT path
        FROM l1c_zip_info 
        WHERE shot_date >= to_date('{start_date}' ,'yyyy-mm-dd')
        AND shot_date <= to_date('{end_date}' ,'yyyy-mm-dd')
        AND tile = any('{tiles}')  
        AND clouds <= {maxcloud}
	"""
	cur.execute(sql)
	con.commit()
	paths = [record[0] for record in cur.fetchall()]
	cur.close()
	con.close()
	return paths

# select sentinel2 l1c zip file path
def select_zip_names(tiles, start_date, end_date, maxcloud):
	tiles ="{" +",".join(tiles)+"}"
	con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
	)
	cur = con.cursor()
	sql = f"""
        SELECT name
        FROM l1c_zip_info 
        WHERE shot_date >= to_date('{start_date}' ,'yyyy-mm-dd')
        AND shot_date <= to_date('{end_date}' ,'yyyy-mm-dd')
        AND tile = any('{tiles}')  
        AND clouds <= {maxcloud}
	"""
	cur.execute(sql)
	con.commit()
	paths = [record[0] for record in cur.fetchall()]
	cur.close()
	con.close()
	return paths

def get_pg_sentinel2_dataframe(args):
    [tiles,start_date,end_date,maxcloud]=args
    con = psycopg2.connect(
        database="sentinel2",
        user="postgres",
        password="12345",
        host="192.168.2.172",
        port="5432"
    )
    cur = con.cursor()
    tilestr ="{" +",".join(tiles)+"}"
    sql = f"""
        SELECT name
        FROM l1c_zip_info 
        WHERE shot_date >= to_date('{start_date}' ,'yyyy-mm-dd')
        AND shot_date <= to_date('{end_date+datetime.timedelta(days=1)}' ,'yyyy-mm-dd')
        AND tile = any('{tilestr}')  
        AND clouds <= {maxcloud}
    """
    cur.execute(sql)
    con.commit()
    names = [record[0] for record in cur.fetchall()]
    cur.close()
    con.close()
    temp_date = start_date
    dates = [temp_date.strftime("%Y%m%d")]
    while temp_date!= end_date:
        temp_date = temp_date + datetime.timedelta(days=1)
        dates.append(temp_date.strftime("%Y%m%d"))
    dataframe = pd.DataFrame(columns=tiles,index=dates)
    for tile in tiles:
        for date in dates:
            name_re = f"S.*_{date}T.*_T{tile}.*\.zip$"
            for name in names:
                if re.match(name_re,name):
                    dataframe[tile][date]=date
    for tile in tiles:
        for j in range(5):
            temp = dataframe[tile][j::5].copy()
            nan_count = list(temp).count(np.nan)
            all_count = len(list(temp))
            if 0<nan_count<all_count:
                for index in temp.index.values:
                    if not isinstance(temp[index],str):
                        dataframe[tile][index]=f"????????" 
            elif nan_count==all_count:
                for index in temp.index.values:
                   
                    dataframe[tile][index] = f""  
    return dataframe

# ui
class my_ui:

    today = datetime.datetime.now()
    tile_name = "Sentinel2数据查询工具"
    width, height = 780, 850
    line_height = 60
    txt_path = os.path.join(os.getcwd(),"history.txt")
    tabel_name = "哨兵数据信息表"
    years = tuple(list(reversed(range(2017,today.year+1))))
    months = tuple(range(1, 12+1))

    def __init__(self):
        self.get_window()
        self.tiles_str = tk.StringVar()
        line_iter = iter(range(50))
        self.select_tiles_frame(next(line_iter))
        self.select_zones_frame(next(line_iter))
        self.select_dates_frame(next(line_iter))
        # self.select_period_frame(next(line_iter))
        self.select_cloud_frame(next(line_iter))
        self.select_bands_frame(next(line_iter))
        # self.select_folder_frame(next(line_iter))
        self.start_button_frame(next(line_iter))
        self.progressbar_frame(next(line_iter))
        self.print_running_frame(next(line_iter))
        self.window.mainloop()

    def get_window(self):
        self.window = tk.Tk()
        self.window.title(self.tile_name)
        screenwidth = self.window.winfo_screenwidth() # 屏幕宽度
        screenheight = self.window.winfo_screenheight() # 屏幕高度
        x = int((screenwidth - self.width) / 2)
        y = int((screenheight - self.height) / 2)
        locat = f"{self.width}x{self.height}+{x}+{y}"
        self.window.geometry(locat) # 大小以及位置
        self.window.resizable(0,0) 
        return

    def get_toplevel(self):
        self.toplevel = tk.Toplevel()
        self.toplevel.title("哨兵数据信息表")
        screenwidth = self.toplevel.winfo_screenwidth() # 屏幕宽度
        screenheight = self.toplevel.winfo_screenheight() # 屏幕高度
        x = int((screenwidth - self.width) / 2)
        y = int((screenheight - self.height) / 2)
        locat = f"{self.width}x{self.height}+{x}+{y}"
        self.toplevel.geometry(locat) # 大小以及位置
        self.toplevel.attributes("-toolwindow", True)
        self.toplevel.attributes("-topmost", True)
        self.toplevel.wm_attributes("-toolwindow", False)
        self.toplevel.wm_attributes("-fullscreen",False)
        self.toplevel.resizable(1,1)
        self.toplevel.sizefrom(who="user")
        # self.toplevel.transient(master=self.window)
        self.toplevel.attributes("-disabled", False)
        self.print_tabel_frame()
        return

    def print_tabel_frame(self):

        frame = tkinter.ttk.Frame(self.toplevel)
        frame.pack(side=tk.TOP)
        args = [self.tiles,self.start_date,self.end_date,self.max_cloud]
        dataframe = get_pg_sentinel2_dataframe(args)
        headers = dataframe.columns.values
        treeview = tkinter.ttk.Treeview(
            # self.toplevel,
            frame,
            columns=headers,
            show='headings',
            height=len(dataframe.index.values),
            selectmode = tk.BROWSE,
        )

        for index,field in enumerate(headers):
            width = 10 * 8
            treeview.column(index,width=width,anchor="center")
            treeview.heading(index,text=field)
        
        for i,index in enumerate(dataframe.index.values):
            values = tuple(dataframe.loc[index,:])
            treeview.insert('', tk.END, values=values) 

        treeview.pack(side=tk.TOP) 


        xscrollbar = tk.Scrollbar(self.toplevel, orient=tk.HORIZONTAL)
        xscrollbar.pack(side=tk.BOTTOM, fill=tk.X)
        # yscrollbar = tk.Scrollbar(self.toplevel, orient=tk.VERTICAL)
        # yscrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # treeview['yscroll'] = yscrollbar.set
        treeview['xscroll'] = xscrollbar.set
        # yscrollbar.config(command=treeview.yview)
        xscrollbar.config(command=treeview.xview)
    
        return

    def select_tiles_frame(self, row):
        frame1 = tkinter.ttk.Frame(self.window)
        frame1.place(x=0,y=self.line_height*row)
        tk.Label(
            frame1,text="图幅列表",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky=tk.W+tk.E)
        frame2 = tkinter.ttk.Frame(frame1)
        frame2.grid(column=1,row=0,sticky=tk.W+tk.E)
        self.tilestr_entry=tk.Entry(
            frame2,
            width=85,
            background = 'white',
            borderwidth = 3,
            relief = 'sunken',
            insertwidth = 3,
            font = ('', '12', ''),
            textvariable=self.tiles_str,
            selectforeground = 'red',
            selectbackground = 'blue',
            selectborderwidth = 0,
            show=None, 
        )
        self.tilestr_entry.pack(side=tk.TOP,fill=tk.NONE)  
        scroll = tk.Scrollbar(
            frame2,
            orient=tk.HORIZONTAL,
            cursor="arrow",
            command=self.tilestr_entry.xview,
            # width=85
        )
        scroll.pack(side=tk.BOTTOM,fill=tk.X, padx=0)
        self.tilestr_entry.config(xscrollcommand=scroll.set)
        return

    def select_zones_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text="省份名称",font=('宋体','14','bold'),height=3,
         ).grid(column=0,row=0,sticky='we')
        # 定义一个Combobox
        values = tuple(get_province_list())
        self.province_combobox=tkinter.ttk.Combobox(
            frame,
            width=17,
            height=len(values),
            state="normal",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=values,
            show=None,
           
        )
        self.province_combobox.current(32)
        self.province_combobox.grid(column=1,row=0,sticky='we')
        self.province_combobox.bind(
            "<<ComboboxSelected>>", self.update_city_box
        )
        tk.Label(
            frame,text="地市名称",font=('宋体','14','bold'),height=3,
         ).grid(column=2,row=0,sticky='we')
        #定义一个Combobox
        values = tuple(get_province_list())
        self.city_combobox=tkinter.ttk.Combobox(
            frame,
            width=22,
            height=len(values),
            state="readonly",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=values,
            show=None
        )
        self.city_combobox.grid(column=3,row=0,sticky='we')
        self.city_combobox.bind(
            "<<ComboboxSelected>>", self.update_county_box
        )
        tk.Label(
            frame,text="县区名称",font=('宋体','14','bold'),height=3,
         ).grid(column=4,row=0,sticky='we')
        #定义一个Combobox
        values = tuple(get_province_list())
        self.county_combobox=tkinter.ttk.Combobox(
            frame,
            width=16,
            height=len(values),
            state="readonly",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=values,
            show=None
        )
        self.county_combobox.grid(column=5,row=0,sticky='we')
        return
    
    def select_dates_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        # start date
        tk.Label(
            frame,text="起始日期",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky=tk.W+tk.E)
        self.start_year_combobox=tkinter.ttk.Combobox(
            frame,
            width=4,
            height=len(self.years),
            state="normal",
            cursor="arrow",
            background = 'white',
            # textvariable="",
            font = ('', '12', ''),
            values=self.years,
            show=None
        )
        self.start_year_combobox.grid(column=1,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame,text="年",font=('宋体','14','bold'),height=3,
        ).grid(column=2,row=0,sticky=tk.W+tk.E)
        self.start_month_combobox=tkinter.ttk.Combobox(
            frame,
            width=2,
            height=len(self.months),
            state="normal",
            cursor="arrow",
            background = 'white',
            # textvariable="",
            font = ('', '12', ''),
            values=self.months,
            show=None
        )
        self.start_month_combobox.bind(
            "<<ComboboxSelected>>", self.update_start_day_combobox
        )
        self.start_month_combobox.grid(column=3,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame, text="月",font=('宋体','14','bold'),height=3,
        ).grid(column=4,row=0,sticky=tk.W+tk.E)
       
        self.start_day_combobox=tkinter.ttk.Combobox(
            frame,
            width=2,
            # height=len(days),
            state="normal",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            # values=days,
            show=None
        )
        self.start_day_combobox.grid(column=5,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame, text="日",font=('宋体','14','bold'),height=3,
        ).grid(column=6,row=0,sticky=tk.W+tk.E)
        
        # end date
        string = "                "
        tk.Label(
            frame,text=f"{string}截至日期",font=('宋体','14','bold'),height=3,
        ).grid(column=7,row=0,sticky=tk.W+tk.E)
        self.end_year_combobox=tkinter.ttk.Combobox(
            frame,
            width=4,
            height=len(self.years),
            state="normal",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=self.years,
            show=None
        )
        self.end_year_combobox.current(self.years.index(self.today.year))
        self.end_year_combobox.grid(column=8,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame,text="年",font=('宋体','14','bold'),height=3,
        ).grid(column=9,row=0,sticky=tk.W+tk.E)
        self.end_month_combobox=tkinter.ttk.Combobox(
            frame,
            width=2,
            height=len(self.months),
            state="normal",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=self.months,
            show=None
        )
        self.end_month_combobox.current(self.months.index(self.today.month))
        self.end_month_combobox.grid(column=10,row=0,sticky=tk.W+tk.E)
        self.end_month_combobox.bind(
            "<<ComboboxSelected>>", self.update_end_day_combobox
        )
        tk.Label(
            frame, text="月",font=('宋体','14','bold'),height=3,
        ).grid(column=11,row=0,sticky=tk.W+tk.E)
     
        self.end_day_combobox=tkinter.ttk.Combobox(
            frame,
            width=2,
            height=1,
            state="normal",
            cursor="arrow",
            background='white',
            textvariable="",
            font = ('', '12', ''),
            values=tuple([self.today.day]),
            show=None
        )
        self.end_day_combobox.current(0)
        self.end_day_combobox.grid(column=12,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame, text="日",font=('宋体','14','bold'),height=3,
        ).grid(column=13,row=0,sticky=tk.W+tk.E)
        return

    def update_start_day_combobox(self,event):
        self.start_year_combobox.get()
        self.start_month_combobox.get()
        day_max=calendar.monthrange(
            int(self.start_year_combobox.get()), 
            int(self.start_month_combobox.get())
        )[1]
        days = tuple(range(1,day_max+1))
        self.start_day_combobox["height"]=len(days)
        self.start_day_combobox["values"]=days
        self.start_day_combobox.current(0)
        return

    def update_end_day_combobox(self,event):
        self.end_year_combobox.get()
        self.end_month_combobox.get()
        day_max=calendar.monthrange(
            int(self.end_year_combobox.get()), 
            int(self.end_month_combobox.get())
        )[1]
        days = tuple(range(1,day_max+1))
        self.end_day_combobox["height"]=len(days)
        self.end_day_combobox["values"]=days
        self.end_day_combobox.current(days.index(day_max))
        return

    def select_period_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text="选择时期",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky=tk.W+tk.E)
        maxyear = datetime.datetime.now().year
        years = tuple(range(2017,maxyear+1))
        self.year_combobox=tkinter.ttk.Combobox(
            frame,
            width=4,
            height=len(years),
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=years,
            show=None
        )
        self.year_combobox.grid(column=1,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame,text="年",font=('宋体','14','bold'),height=3,
        ).grid(column=2,row=0,sticky=tk.W+tk.E)
        months = tuple(range(1,13))
        self.month_combobox=tkinter.ttk.Combobox(
            frame,
            width=2,
            height=len(months),
            state='readonly',
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=months,
            show=None
        )
        self.month_combobox.grid(column=3,row=0,sticky=tk.W+tk.E)
        tk.Label(
            frame, text="月",font=('宋体','14','bold'),height=3,
        ).grid(column=4,row=0,sticky=tk.W+tk.E)
        periods = ("1501","1502","3000")
        textvariable = tk.StringVar()
        textvariable.set("3000")
        self.period_combobox=tkinter.ttk.Combobox(
            frame,
            width=4,
            height=len(periods),
            state='readonly',
            cursor="arrow",
            background='white',
            textvariable=textvariable,
            font = ('', '12', ''),
            value=periods,
            show=None,
        )
        self.period_combobox.current(2)
        self.period_combobox.grid(column=5,row=0,sticky=tk.W+tk.E)
        # self.period_combobox.insert(0, "默认文本...")
        tk.Label(
            frame, text="时期",font=('宋体','14','bold'),height=3,
        ).grid(column=6,row=0,sticky=tk.W+tk.E)
        return

    def update_city_box(self, event):
        province = self.province_combobox.get()
        city_list = select_city_list(province)
        self.city_combobox["value"] = city_list
        self.city_combobox["height"] = len(city_list)
        return
    
    def update_county_box(self, event):
        province = self.province_combobox.get()
        city = self.city_combobox.get()
        county_list = select_county_list(province, city)
        self.county_combobox["value"] = county_list
        self.county_combobox["height"] = len(county_list)
        return
    
    def select_bands_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text="波段列表",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        bands = tk.StringVar()
        bands.set("2-3-4-5-6-7-8-12")
        self.bands_entry=tk.Entry(
            frame,
            width=51,
            background = 'white',
            borderwidth = 3,
            relief = 'sunken',
            insertwidth = 3,
            font = ('', '12', ''),
            textvariable=bands,
            selectforeground = 'red',
            selectbackground = 'blue',
            selectborderwidth = 0,
            # show="2-3-4-5-6-7-8-8A-11-12-99"
        )
        self.bands_entry.grid(column=1,row=0,sticky='we')
        return

    def select_cloud_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=self.line_height*row)
        tk.Label(
            frame,text=f"最大云量",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        max_clound = tk.IntVar()
        max_clound.set(100)
        self.maxcloud_scale=tk.Scale(
            frame, 
            # label="MaxCloud",    # 标签
            variable=max_clound, 	# 值
            from_=0,    #  最小值， 记住是from_， from是关键字
            to=100,       #  最大值
            resolution=1,  # 步进值
            show=True,   # 是否在上面显示值
            orient=tk.HORIZONTAL,  # 水平显示
            length=680,  # 滑块长度
            # command=lambda value, key=k:self.get_value(value, key)
        )
        self.maxcloud_scale.grid(column=1,row=0,sticky='we')
        return

    def start_button_frame(self, row):
        s = tkinter.ttk.Style()
        s.configure("1.TFrame",background='white')
        frame=tkinter.ttk.Frame(
            self.window,style="1.TFrame",width=self.width,height=60)
        frame.place(x=0,y=self.line_height*row)
        self.start_button=tk.Button(
            frame,
            text="开始查询",
            font=('','14','bold'),
            command=lambda: self.thread_it(self.run_main),
        )
        self.start_button.place(relx=0.5,rely=0.5,anchor='center')
        return

    def progressbar_frame(self,row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=60*row)
        tk.Label(
            frame,text="运行进度",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        self.progressbar=tkinter.ttk.Progressbar(
            frame,
            length=680,
            # maximum=100,
            value=0,
            cursor='spider',
            # mode="determinate",
            mode="indeterminate",
            orient=tk.HORIZONTAL,
        )
        self.progressbar.grid(column=1,row=0,sticky='we')
        # self.progressbar.pack(side=tk.LEFT+tk.TOP,fill=tk.NONE)
        return

    def print_running_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=60*row)
        tk.Label(
            frame,text="运行信息",font=('宋体','14','bold'),
        ).grid(column=0,row=0,sticky='we')
        # ).pack(side=tk.LEFT+tk.TOP,fill=tk.NONE)
        self.scrolled_text = scrolledtext.ScrolledText(
			frame, 
			state='normal',
            wrap = tk.WORD,
            # font=('Times New Roman', 12),
            font="TkFixedFont",
			width=95, 
			height=28,
        ) 
        self.scrolled_text.tag_config('INFO', foreground='black')
        self.scrolled_text.tag_config('DEBUG', foreground='gray')
        self.scrolled_text.tag_config('WARNING', foreground='orange')
        self.scrolled_text.tag_config('ERROR', foreground='red')
        self.scrolled_text.tag_config('CRITICAL', foreground='red', underline=1)
        self.scrolled_text.grid(column=1,row=0,rowspan=20,sticky='we')
        # self.scrolled_text.pack(side=tk.LEFT,fill=tk.NONE) 
        return
    
    def select_folder_frame(self, row):
        frame=tkinter.ttk.Frame(self.window)
        frame.place(x=0,y=60*row)
        tk.Label(
            frame,text="3A目录",font=('宋体','14','bold'),height=3,
        ).grid(column=0,row=0,sticky='we')
        if os.path.exists(self.txt_path):
            lines = []
            with open(self.txt_path,"r") as file:
                for line in file:
                    line=line.strip('\n')#删除换行符
                    lines.append(line)
            values = tuple(lines)
        else:
            values = tuple([])
        self.folder_combobox=tkinter.ttk.Combobox(
            frame,
            width=83,
            height=len(values),
            state="normal",
            cursor="arrow",
            background = 'white',
            textvariable="",
            font = ('', '12', ''),
            values=values,
            show=None,  
        )
        self.folder_combobox.grid(column=1,row=0,sticky='we')
        return

    def thread_it(self,func,*args):
        t = threading.Thread(target=func, args=args)
        # 守护 !!!
        t.setDaemon(True)
        # 启动
        t.start()
        # 阻塞--卡死界面！
        # t.join()
        return

    def run_main(self):
        self.progressbar.start()
        start = time.time()
        datetime_str = datetime.datetime.now()
        datetime_str = datetime_str.strftime('%Y-%m-%d %H:%M:%S')
        string = f"\n{datetime_str}>正在查询所选图幅..."
        self.scrolled_text.insert(tk.END, string)
        self.window.update()

        tiles_str = self.tilestr_entry.get()
        if tiles_str!="":
            self.tiles = [tile.upper() for tile in tiles_str.split("-")]
        else:
            province = self.province_combobox.get()
            city = self.city_combobox.get()
            if city == "":
                self.tiles = get_province_tiles(province)
            else:
                county = self.county_combobox.get()
                if county == "":
                    self.tiles = get_city_tiles(province, city)
                else:
                    self.tiles = get_county_tiles(province, city, county)

        if not self.tiles:
            tk.messagebox.showwarning('Waring', '未选择图幅！')
            return self.progressbar.stop()
            
        datetime_str = datetime.datetime.now()
        datetime_str = datetime_str.strftime('%Y-%m-%d %H:%M:%S')
        string = f"\n{datetime_str}>{len(self.tiles)}个图幅:{self.tiles}"
        self.scrolled_text.insert(tk.END, string)
        self.window.update()

        start_year = self.start_year_combobox.get()
        start_month = self.start_month_combobox.get()
        start_day = self.start_day_combobox.get()
        if not (start_year and start_month and start_day):
            tk.messagebox.showerror('Error', '开始时期未选择完整！')
            return self.progressbar.stop()
        start_date = f"{start_year}-{start_month}-{start_day}"
        datetime_str = datetime.datetime.now()
        datetime_str = datetime_str.strftime('%Y-%m-%d %H:%M:%S')
        string = f"\n{datetime_str}>日期:{start_date}"
        self.scrolled_text.insert(tk.END, string)
        self.window.update()

        end_year = self.end_year_combobox.get()
        end_month = self.end_month_combobox.get()
        end_day = self.end_day_combobox.get()
       
        if not (end_year and end_month and end_day):
            tk.messagebox.showerror('Error', '截至时期未选择完整！')
            return self.progressbar.stop()
        end_date = f"{end_year}-{end_month}-{end_day}"
        datetime_str = datetime.datetime.now()
        datetime_str = datetime_str.strftime('%Y-%m-%d %H:%M:%S')
        string = f"\n{datetime_str}>日期:{end_date}"
        self.scrolled_text.insert(tk.END, string)
        self.window.update()

        self.max_cloud = self.maxcloud_scale.get()
        datetime_str = datetime.datetime.now()
        datetime_str = datetime_str.strftime('%Y-%m-%d %H:%M:%S')
        string = f"\n{datetime_str}>最大含云量:{self.max_cloud}"
        self.scrolled_text.insert(tk.END, string)
        self.window.update()

        bands_str = self.bands_entry.get()
        if bands_str == "":
            tk.messagebox.showerror('Error', '未选择存在波段！')
            return self.progressbar.stop()
        bands = bands_str.split("-")
        datetime_str = datetime.datetime.now()
        datetime_str = datetime_str.strftime('%Y-%m-%d %H:%M:%S')
        string = f"\n{datetime_str}>波段列表:{bands}"
        self.scrolled_text.insert(tk.END, string)
        self.window.update()

        self.start_date=datetime.datetime.strptime(start_date,'%Y-%m-%d')
        self.end_date=datetime.datetime.strptime(end_date,'%Y-%m-%d')

        self.get_toplevel()

        self.progressbar.stop()
        # tk.messagebox.showinfo('Message', f'查询完成！耗时：{time.time()-start}')
        return




if __name__ == "__main__":
    my_ui()